package com.ziyun.pop.modules.capital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziyun.pop.modules.capital.dao.MerchantOrderAccountDao;
import com.ziyun.pop.modules.capital.entity.MerchantApplyCashEntity;
import com.ziyun.pop.modules.capital.entity.MerchantOrderAccountEntity;
import com.ziyun.pop.modules.capital.entity.SupplierApplyCashRuleEntity;
import com.ziyun.pop.modules.capital.service.MerchantOrderAccountService;
import com.ziyun.pop.modules.capital.service.SupplierApplyCashService;
import com.ziyun.pop.modules.supp.entity.SellerInfoEntity;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service("merchantOrderAccountService")
public class MerchantOrderAccountServiceImpl extends ServiceImpl<MerchantOrderAccountDao, MerchantOrderAccountEntity>
        implements MerchantOrderAccountService {

    @Autowired
    private SupplierApplyCashService supplierApplyCashService;

    @Autowired
    private SellerInfoService sellerInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Integer sellerId = Integer.parseInt(params.get("sellerId").toString());

        List<Integer> selleInfoIdList = this.getSellInfoList(sellerId);

        // 是否冻结 0冻结 1 非冻结
        Integer isFreeze = Integer.parseInt(params.get("isFreeze").toString());

        Integer merchantType = Integer.parseInt(params.get("merchantType").toString());


        //下单时间
        List<String> orderCreateTimeList = new ArrayList<>();
        Date beginCreateTime = null;
        Date endCreateTime = null;
        if (params.get("orderCreateTime") != null) {
            orderCreateTimeList = (List<String>) params.get("orderCreateTime");
            beginCreateTime = DateUtils.stringToDate(orderCreateTimeList.get(0), DateUtils.DATE_PATTERN);
            endCreateTime = DateUtils.stringToDate(orderCreateTimeList.get(1), DateUtils.DATE_PATTERN);
        }

        //收货时间  根据商户类型 进行判断
        int day = 0; // 天数
        int calculationWay = 0;// 1月结 2日结
        if (merchantType.intValue() == 0) { // 小b 收货时间节点判断
            calculationWay = 2;
            day = 2;
        } else if (merchantType.intValue() == 1) { // 工厂 收货时间节点判断
            SupplierApplyCashRuleEntity applyCashRule = this.supplierApplyCashService.getOne(new QueryWrapper<SupplierApplyCashRuleEntity>()
                    .eq("factory_id", sellerId));
            if (applyCashRule == null) {
                calculationWay = 1;
                day = 25;
            } else {
                calculationWay = applyCashRule.getRuleType();
                if (calculationWay == 1) {
                    day = applyCashRule.getRuleMonth();
                } else {
                    day = applyCashRule.getRuleDay();
                }
            }
        }

        List<String> orderReceiveTimeList = new ArrayList<>();
        Date beginReceiveTime = null;
        Date endReceiveTime = null;
        if (params.get("receivedTime") != null) {
            orderReceiveTimeList = (List<String>) params.get("receivedTime");
            beginReceiveTime = DateUtils.stringToDate(orderReceiveTimeList.get(0), DateUtils.DATE_PATTERN);
            endReceiveTime = DateUtils.stringToDate(orderReceiveTimeList.get(1), DateUtils.DATE_PATTERN);
        }

        IPage<MerchantOrderAccountEntity> page = this.page(new Query<MerchantOrderAccountEntity>(params).getPage(),
                new QueryWrapper<MerchantOrderAccountEntity>()
                        //.eq("seller_id", params.get("sellerId"))
                        .in("seller_id", selleInfoIdList)
                        .eq("fund_state", 0) // 仅查询未提现的
                        .eq("status", "finish") // 已完成
                        .eq("merchant_type", params.get("merchantType"))
                        .eq(params.get("orderAccountId") != null && !params.get("orderAccountId").equals(""), "order_account_id", params.get("orderAccountId"))
                        .eq(params.get("orderId") != null && !params.get("orderId").equals(""), "order_id", params.get("orderId"))
                        .apply(calculationWay == 2 && isFreeze.intValue() == 0, //日结 冻结
                                "DATEDIFF(DATE(now()), DATE(received_time)) < {0} ", day)
                        .apply(calculationWay == 2 && isFreeze.intValue() == 1, //日结 非冻结
                                "DATEDIFF(DATE(now()), DATE(received_time)) >= {0} ", day)
                        .apply(calculationWay == 1 && isFreeze.intValue() == 0, //月结 冻结
                                "DATEDIFF(DATE(now()), DATE_ADD(received_time,interval -day(received_time)+1 day) ) < day(LAST_DAY(received_time)) +{0} ", day)
                        .apply(calculationWay == 1 && isFreeze.intValue() == 1, // 月结 非冻结
                                "DATEDIFF(DATE(now()), DATE_ADD(received_time,interval -day(received_time)+1 day) ) >= day(LAST_DAY(received_time)) +{0} ", day)
                        .between(orderCreateTimeList.size() > 1, "order_create_time", beginCreateTime, endCreateTime)
                        .between(orderReceiveTimeList.size() > 1, "received_time", beginReceiveTime, endReceiveTime)
        );
        return new PageUtils(page);
    }

    /**
     * 获取小b 最后收货时间节点
     *
     * @param currentDate
     * @return
     */
    private Date getSmallBReceiveTimeNode(Date currentDate) {
        return DateUtils.addDateDays(DateUtils.getDateEnd(currentDate), -2);
    }

    /**
     * 获取工厂 最后收货时间节点
     *
     * @param currentDate
     * @param sellerId
     * @return
     */
    private Date getFactoryReceiveTimeNode(Date currentDate, Integer sellerId) {
        // 先查询规则
        SupplierApplyCashRuleEntity applyCashRule = this.supplierApplyCashService.getOne(new QueryWrapper<SupplierApplyCashRuleEntity>()
                .eq("factory_id", sellerId));
        if (applyCashRule == null) { // 为空 则采用月结 25号

        }
        return null;
    }


    @Override
    public int updateBatchByParams(Map<String, Object> whereParams) {
        return this.baseMapper.updateBatchByParams(whereParams);
    }

    @Override
    public Map<String, Object> orderList(Map<String, Object> params) {

        Map<String, Object> rs = new HashMap<>();

        Integer sellerId = Integer.parseInt(params.get("sellerId").toString());

        List<Integer> selleInfoIdList = this.getSellInfoList(sellerId);

        // 是否冻结 0冻结 1 非冻结
        Integer isFreeze = Integer.parseInt(params.get("isFreeze").toString());

        IPage<MerchantOrderAccountEntity> page = this.page(new Query<MerchantOrderAccountEntity>(params).getPage(),
                new QueryWrapper<MerchantOrderAccountEntity>()
                        //.eq("seller_id", params.get("sellerId"))
                        .in("seller_id", selleInfoIdList)
                        .eq("fund_state", 0) // 仅查询未提现的
                        .eq("status", "finish") // 已完成
                        .eq("merchant_type", 0)
                        .apply(isFreeze.intValue() == 0, //日结 冻结
                                "DATEDIFF(DATE(now()), DATE(received_time)) < {0} ", 2)
                        .apply(isFreeze.intValue() == 1, //日结 非冻结
                                "DATEDIFF(DATE(now()), DATE(received_time)) >= {0} ", 2)

        );

        Map totalMap =  this.getMap(new QueryWrapper<MerchantOrderAccountEntity>()
                .select("sum(total_amount+cost_freight) total")
                .in("seller_id", selleInfoIdList)
                .eq("fund_state", 0) // 仅查询未提现的
                .eq("status", "finish") // 已完成
                .eq("merchant_type", 0)
                .apply(isFreeze.intValue() == 0, //日结 冻结
                        "DATEDIFF(DATE(now()), DATE(received_time)) < {0} ", 2)
                .apply(isFreeze.intValue() == 1, //日结 非冻结
                        "DATEDIFF(DATE(now()), DATE(received_time)) >= {0} ", 2)
        );
        if (totalMap != null){
            rs.put("totalAmount", totalMap.get("total"));
        }else {
            rs.put("totalAmount", 0);
        }
        rs.put("page", page);
        return rs;
    }

    @Override
    public List<Integer> getSellInfoList(Integer sellerId){
        //先查询用户相关信息
        SellerInfoEntity sellerInfo = this.sellerInfoService.getById(sellerId);
        // 小B 只能 连锁店总店提现
        if (sellerInfo.getSellerType().equals("0") && sellerInfo.getMainSellerId().intValue() > 0) {
            throw new RRException("连锁店仅允许主店提现");
        }
        List<Integer> selleInfoIdList = new ArrayList<Integer>();
        if (sellerInfo.getSellerType().equals("0") && sellerInfo.getMainSellerId().intValue() == 0) {
            // 查询该店是否存在分店
            List<SellerInfoEntity> selleInfoObjectList = this.sellerInfoService.list(new QueryWrapper<SellerInfoEntity>()
                    .select("seller_id")
                    .eq("main_seller_id", sellerId)
                    .eq("disabled", 0));
            Iterator<SellerInfoEntity> listIt = selleInfoObjectList.iterator();
            while (listIt.hasNext()) {
                selleInfoIdList.add(listIt.next().getSellerId());
            }
        }

        selleInfoIdList.add(sellerId);

        return selleInfoIdList;
    }

}
